/* 
 * File:   Terrain.cpp
 * Author: aljosa
 * 
 * Created on June 22, 2010, 6:17 PM
 */

#include <SDL/SDL.h>
#include <SDL/SDL_image.h>

#include "Terrain.h"
#include "messages.h"


namespace xEngine
{
  namespace Resources
  {
      Terrain::Terrain() {
     /*     MAPX_X = 32;
          MAP_Z = 32;
          MAP_SCALE = 20.0f;*/
      }


      Terrain::~Terrain() {
      }
      
      bool Terrain::init() {

          // Terrain initialization

          if ( !load ("data/terrain.bmp") ) { // Loading terrain data successfull?
              Messages::initMessage("terrain", false); // NO!
              return false;
          }

          // Other initialization
          // ../


          // Everything OK
          Messages::initMessage("terrain", true);
          return true;
      }
      
      bool Terrain::load(string filename) {// Load image file and set terrain geometry
          SDL_Surface *imgSurface = NULL; // Surface



          // Load height image
          if ( (imgSurface = IMG_Load(filename.c_str())) == NULL ){
              Messages::errorMessage("Terrain loading failed. Is image " + filename + " present?");
              return false;
          }

          SDL_LockSurface(imgSurface);

          //imgSurface = SDL_DisplayFormat(imgSurface);


          int index = 0;
          int currentVertex;

          unsigned char *pixels = (unsigned char*)imgSurface->pixels;

          // Loop over all vertices
         for ( int z=0; z<MAP_Z; z++ ) {
              for ( int x=0; x<MAP_X; x++ ) {
                  //currentVertex = z * MAP_X + x;

                  // Set the colors
                 // colorArray[currentVertex][0] = colorArray[currentVertex][1] = colorArray[currentVertex][2] =

                  vertices[x][z][0] = float(x)*MAP_SCALE;
                  vertices[x][z][1] = (float) pixels[(z*MAP_Z+x)*3];
                  vertices[x][z][2] = -float(z)*MAP_SCALE;

              }
          }

              for ( int z=0; z<32; z++ ) {
              for ( int x=0; x<32; x++ ) {
                  //currentVertex = z * MAP_X + x;

                  // Set the colors
                 // colorArray[currentVertex][0] = colorArray[currentVertex][1] = colorArray[currentVertex][2] =



                //  cout <<x <<"  ";
                //  cout <<z<<"  ";
                  cout <<(float) pixels[(z*MAP_Z+x)*3]<<" ";
                //  cout<<" | ";
             //     cout<< (unsigned)pixels[z+x] <<' ';

              }
              cout<<endl;

          }
          // Image in memory
//          imgSurface->pixels[0];


          // Release surface
          SDL_FreeSurface(imgSurface);

          return true;
          
      }

      void Terrain::shutDown() {

      }
  }
}

